const express = require('express');
const router = express.Router();

const bodyParser = require('body-parser');
const loginSQL = require('../../db/loginSQL');
const registerSQL = require('../../db/registerSQL');
const data = require('../data');
const chinaTime = require('china-time');
let UPDic = data.UPDic;

router.post('/register', bodyParser.json(), (req, res) => {
    // 检查用户名与密码是否为空
    if (!req.body["userAccount"]
        || typeof req.body["userAccount"] != "string"
        || !req.body["userAccount"].length) {
        res.json({
            err: 1,
            message: '用户名为空'
        })
    } else if (!req.body["password"]
        || typeof req.body["password"] != "string"
        || !req.body["password"].length) {
        res.json({
            err: 1,
            message: '密码为空'
        })
    } else {
        let userAccount = req.body["userAccount"];
        let password = req.body["password"];
        let userTime = chinaTime('YYYYMMDD');
        // 下方改数据库操作代码

        //第二次操作，插如account表
        function registerInsert () {
            // UPDic[userAccount] = password;
            registerSQL.register(userAccount, password, userTime, (result) => {
                console.log('result in register router:');
                console.log(result);

                // 这里需要再查找一次account表获取返回值
                res.json({
                    err: 200,
                    message: '注册成功',
                    userID: 1,
                    userAccount,
                    password,
                    userPower: 0
                })
            })
        }

        //第一次操作
        function registerTestName (data) {
            // if (UPDic[userAccount] == userAccount) {
            if (data.length != 0) {
                res.json({
                    err: 1,
                    message: '用户名已存在'
                })
            } else {
                //第二次数据库操作语句，插入，更改函数
                // loginSQL.login(userAccount, password, registerInsert);
                registerInsert();
            }
        }

        //等会在这里修改就好，第一次数据库操作
        loginSQL.login(userAccount, registerTestName);

    }
})

module.exports = router;